package com.yunmang.activity.exception;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.NameBean;
import com.yunmang.entity.OrderDetailBean;
import com.yunmang.entity.ParameterEntity.AddExceptionBean;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/5/23.
 */
public class ExceptionReportActivity extends BaseActivity implements OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.et_hdbh_search)
    EditText etSearch;
    @InjectView(R.id.image_scan)
    ImageView ivScan;
    @InjectView(R.id.ll_search)
    LinearLayout llSearch;
    @InjectView(R.id.search)
    Button btnSearch;
    @InjectView(R.id.ll_container)
    LinearLayout llContainer;
    @InjectView(R.id.ll_top)
    LinearLayout llTop;
    @InjectView(R.id.order_hdbh)
    TextView orderHdbh;

    @InjectView(R.id.tv_start)
    TextView tvStart;

    @InjectView(R.id.tv_end)
    TextView tvEnd;
    @InjectView(R.id.tv_goosname)
    TextView tvGoosname;
    @InjectView(R.id.tv_goods_number)
    TextView tvGoodsNumber;
    @InjectView(R.id.tv_consignee_name)
    TextView tvConsigneeName;
    @InjectView(R.id.tv_consignee_phone)
    TextView tvConsigneePhone;
    @InjectView(R.id.vline)
    View vline;
    @InjectView(R.id.btn_add)
    TextView btnAdd;
    @InjectView(R.id.et_exception_number)
    EditText etExceptionNumber;
    @InjectView(R.id.et_charge_person)
    EditText etChargePerson;
    @InjectView(R.id.et_exception_reason)
    EditText etExceptionResult;
    @InjectView(R.id.rl_exception_category)
    RelativeLayout rlExceptionCategory;
    @InjectView(R.id.rl_exception_accident)
    RelativeLayout rlExceptionAccident;
    @InjectView(R.id.iv_arror)
    ImageView ivArror;
    @InjectView(R.id.tv_accident)
    TextView tvAccident;
    @InjectView(R.id.tv_exception_category)
    TextView tvExceptionCategory;
    private AlertView categoryAlert, accidentAlert;
    private Subscriber<NameBean> exceptionSubscriber;
    private Subscriber<OrderDetailBean> subscriber;
    private int accident = 0, billid, exceptioncategory;

    @Override
    public int getLayoutId() {
        return R.layout.activity_exception_report;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        initToolbar();
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("异常上报");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void initData() {

    }


    @OnClick({R.id.rl_exception_accident, R.id.rl_exception_category, R.id.search, R.id.image_scan, R.id.btn_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_exception_accident:
                alertShow2();
                break;
            case R.id.rl_exception_category:
                alertShow1();
                break;
            case R.id.btn_add:

                String exception_num = CommonUtils.getTextViewValue(etExceptionNumber);
                String exception_reason = CommonUtils.getTextViewValue(etExceptionResult);
                String chargePerson = CommonUtils.getTextViewValue(etChargePerson);
                String hdbh = CommonUtils.getTextViewValue(orderHdbh);
                if(TextUtils.isEmpty(exception_num)){
                    showToast("请输入异常件数");
                    return;
                }
                String injson = getJsonData(exception_num,exception_reason,chargePerson,hdbh);
                addException(injson);
                break;
            case R.id.search:
                String search = CommonUtils.getTextViewValue(etSearch);
                if (TextUtils.isEmpty(search)) {
                    showToast("请输入单号");
                    return;
                }
                getOrderDetail(search);
                break;
            case R.id.image_scan:
                CommonUtils.onScanBarcode(this);
                break;
        }
    }

    private String getJsonData(String exception_num, String exception_reason, String chargePerson, String hdbh) {

        Gson gson = new Gson();
        AddExceptionBean addBean = new AddExceptionBean();
        addBean.setNumbers(Integer.parseInt(exception_num));
        addBean.setApplyReason(exception_reason);
        addBean.setChargeName(chargePerson);
        addBean.setUserId(AppConstant.userid);
        addBean.setHdbh(hdbh);
        addBean.setBillId(billid + "");
        addBean.setChargeDepartmentId(AppConstant.orgInfo.getId());
        addBean.setClaimAmount("0");
        addBean.setExceptionCategory(exceptioncategory);
        addBean.setDamage("");
        addBean.setApproveNote("");
        addBean.setCarrierVehicle("");
        addBean.setAccidentType(accident);
        Log.e("json", gson.toJson(addBean));
        return gson.toJson(addBean);
    }

    private void addException(String injson) {
        showWaitingDialog("数据上传中……");
        exceptionSubscriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                hideWaitingDialog();
                showToast("异常上报失败");
            }

            @Override
            public void onNext(NameBean nameBean) {
                Log.e("code", nameBean.getCode() + "");
                hideWaitingDialog();
                if (nameBean.getCode() == 200) {
                    clearUI();
                    showToast("异常上报成功");
                } else {
                    showToast("异常上报失败");
                }
            }
        };
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), injson);
        HttpUtils.getInstance().addException(exceptionSubscriber, body);

    }

    private void getOrderDetail(String search) {
        showWaitingDialog("数据获取中……");
        subscriber = new Subscriber<OrderDetailBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                showToast("获取失败");
                hideWaitingDialog();
            }

            @Override
            public void onNext(OrderDetailBean orderDetailBean) {
                hideWaitingDialog();
                if (orderDetailBean.getCode() == 200) {
                    fillUI(orderDetailBean);
                } else {
                    showToast("无数据");
                }
            }
        };
        HttpUtils.getInstance().getOrderDetail(subscriber, search, AppConstant.orgInfo.getId() + "");
    }

    private void fillUI(OrderDetailBean orderDetailBean) {
        OrderDetailBean.ModelBean model = orderDetailBean.getModel();
        tvStart.setText(model.getStartDepartName());
        tvEnd.setText(model.getEndDepartName());
        orderHdbh.setText(model.getBill().getHdbh());
        tvGoosname.setText(model.getGoodsList().get(0).getGoodsName());
        tvGoodsNumber.setText(model.getBill().getQuantity() + "");
        tvConsigneeName.setText(model.getContact().getConsignee());
        tvConsigneePhone.setText(model.getContact().getConsigneePhone());
        billid = model.getBill().getId();
    }

    private void clearUI() {
        tvStart.setText("");
        tvEnd.setText("");
        orderHdbh.setText("");
        tvGoosname.setText("");
        tvGoodsNumber.setText("");
        tvConsigneeName.setText("");
        tvConsigneePhone.setText("");
        etSearch.setText("");
        etChargePerson.setText("");
        etExceptionResult.setText("");
        etExceptionNumber.setText("");

    }

    public void alertShow1() {
        categoryAlert = new AlertView("标题", null, "取消", null, new String[]{"到货异常", "发车异常"}, this, AlertView.Style.ActionSheet, this);
        categoryAlert.show();
    }

    public void alertShow2() {
        accidentAlert = new AlertView("标题", null, "取消", null, new String[]{"货损", "货丢", "其它"}, this, AlertView.Style.ActionSheet, this);
        accidentAlert.show();
    }

    private String[] exceptionArray = new String[]{"到货异常", "发车异常"};
    private String[] accidentArray = new String[]{"货损", "货丢", "其它"};

    @Override
    public void onItemClick(Object o, int position) {
        if (o == categoryAlert && position != AlertView.CANCELPOSITION) {
            exceptioncategory = position;
            tvExceptionCategory.setText(exceptionArray[position]);
        } else if (o == accidentAlert && position != AlertView.CANCELPOSITION) {
            accident = position;
            tvAccident.setText(accidentArray[position]);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            } else {
                etSearch.setText(result.getContents());
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

}
